package org.brownflat.lighthouse.monitor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executor;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

@Service("monitoringService")
public class SimpleMonitoringService implements MonitoringService {

    private static final Logger LOG = Logger.getLogger(SimpleMonitoringService.class);

    @Autowired
	private Executor executor;

	private List<LighthouseTask> active = new ArrayList<LighthouseTask>();
	private List<LighthouseTask> paused = new ArrayList<LighthouseTask>();

	public void addTask(LighthouseTask task) {
		this.paused.add(task);
	}

    public void setExecutor(Executor executor) {
        this.executor = executor;
    }
	
	public List<LighthouseTask> activeTasks() {
		return active;
	}

    @Override
    public List<LighthouseTask> allTasks() {
        ArrayList<LighthouseTask> tasks = new ArrayList<LighthouseTask>();
        tasks.addAll(activeTasks());
        tasks.addAll(pausedTasks());
        return tasks;
    }

    public List<LighthouseTask> pausedTasks() {
		return paused;
	}
		
	@Override
	public boolean stop() {
        LOG.info("Stopping all tasks");
		for (Iterator iterator = active.iterator(); iterator.hasNext();) {
			LighthouseTask task = (LighthouseTask) iterator.next();
			paused.add(task);
			iterator.remove();
		}
		return true;
	}
	
	@Override
	public boolean stop(String name) {
		for (Iterator iterator = active.iterator(); iterator.hasNext();) {
			LighthouseTask task = (LighthouseTask) iterator.next();
			if(task.getName().equals(name)) {
				paused.add(task);
				iterator.remove();
				return true;
			}
		}
		return false;
	}
	
	@Override
	public boolean start() {
        LOG.info("Starting all tasks");
		for (Iterator iterator = paused.iterator(); iterator.hasNext();) {
			LighthouseTask task = (LighthouseTask) iterator.next();
			active.add(task);
			iterator.remove();			
		}
		return true;
	}

    @Override
    public boolean clearAll() {
        stop();
        LOG.info("Removing all tasks");
        paused.clear();
        return true;
    }

    @Override
	public boolean start(String name) {
		for (Iterator iterator = paused.iterator(); iterator.hasNext();) {
			LighthouseTask task = (LighthouseTask) iterator.next();
			if(task.getName().equals(name)) {
				active.add(task);
				iterator.remove();
				return true;
			}
		}
		return false;
	}

	public void run() {
        LOG.debug("Monitoring service running tasks");
		for (LighthouseTask task : active) {
			LOG.debug("Executing " + task.getName());
			executor.execute(task);
		}
	}
}
